/////////////////////////////////////////////////////////
//                                                     //
// Copyright (c) 2016年 上证云平台. All rights reserved. //
//                                                     //
/////////////////////////////////////////////////////////

#import "TrendChartViewController.h"
#if __has_include("MChartView.h")

#import "MChartView.h"
#import "MApi.h"

@interface TrendChartViewController ()<UIActionSheetDelegate>
@property (nonatomic, strong) UISegmentedControl *seg;
@property (nonatomic, strong) MOHLCChartView *chartView;
@property (nonatomic, weak) NSTimer *timer;
@end

@implementation TrendChartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    
    self.seg = [[UISegmentedControl alloc] initWithItems:@[@"分时", @"五日"]];
    self.seg.selectedSegmentIndex = 0;
    [self.seg addTarget:self action:@selector(segChanged:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.seg];

    self.chartView = [[MOHLCChartView alloc] initWithFrame:CGRectZero];
    self.chartView.code = @"835185.bz";
    
    MTrendChartTheme *theme = [MChartTheme trendChartTheme];
    theme.type = MTrendChartTypeOneDay;
    self.chartView.theme = theme;
    
    MTrendChartPlot *plot = [MTrendChartPlot new];
    plot.lastBlinkDot = ({
        MChartDotView *dot = [MChartDotView blinkDot];
        dot.color = [UIColor yellowColor];
        dot;
    });
    plot.type = MTrendChartTypeOneDay;
    self.chartView.majorPlots = @[plot];
    
    MVOLPlot *volPlot = [MVOLPlot new];
    self.chartView.minorPlots = @[volPlot,[MDDXPlot new],[MDDYPlot new],[MDDZPlot new],[MBBDPlot new],[MRatioBSPlot new]];
    
//    self.chartView.options = @{
//                               @"CUSTOM_DATETIME" : @[@"09:30", @"11:30/13:00", @"15:00"],
//                               @"FIVEDAY_LINE_CONTINUOUS" : @YES,
//                               @"Y_AXIS_PRICE_LABELS_HIDDEN" : @[@NO, @YES, @NO, @YES, @NO],
//                               @"Y_AXIS_UDRATE_LABELS_HIDDEN" : @[@NO, @YES, @NO, @YES, @NO],
//                               @"Y_AXIS_VOLUME_LABELS_HIDDEN" : @[@NO, @YES, @NO, @YES, @NO]
//                               };
//    self.chartView.gradientColors = @[[[UIColor redColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor orangeColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor yellowColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor greenColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor blueColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor magentaColor] colorWithAlphaComponent:0.3],
//                                      [[UIColor purpleColor] colorWithAlphaComponent:0.3]
//                                      ];
//    self.chartView.gradientLocations = (CGFloat []){ 0.0, 0.9, 1.0 };
    
//    self.chartView.yAxisLabelInside = NO;
//    self.chartView.yAxisFont = [UIFont boldSystemFontOfSize:17];
//    self.chartView.borderWidth = 5;
//    self.chartView.borderColor = [UIColor whiteColor];
//    self.chartView.insideLineWidth = 2;
//    self.chartView.insideLineColor = [UIColor purpleColor];
//    self.chartView.xAxisFont = [UIFont boldSystemFontOfSize:12.0];
//    self.chartView.xAxisTextColor = [UIColor redColor];
//    self.chartView.priceRiseTextColor = [UIColor yellowColor];
//    self.chartView.priceFlatTextColor = [UIColor greenColor];
//    self.chartView.priceDropTextColor = [UIColor brownColor];
//    self.chartView.volumeTextColor = [UIColor yellowColor];
//    self.chartView.rangeRiseTextColor = [UIColor orangeColor];
//    self.chartView.rangeFlatTextColor = [UIColor purpleColor];
//    self.chartView.rangeDropTextColor = [UIColor redColor];
//    self.chartView.currentLineWidth = 5;
//    self.chartView.currentLineColor = [UIColor blueColor];
//    self.chartView.averageLineColor = [UIColor orangeColor];
//    self.chartView.averageLineWidth = 5;
    self.chartView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin| UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.chartView];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startEnquiry:) name:MChartDidStartEnquiryNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(endEnquiry:) name:MChartDidEndEnquiryNotification object:nil];
    
    UIButton * button2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button2.frame = CGRectMake(0, 0, 50, 20);
    button2.backgroundColor = [UIColor yellowColor];
    [button2 setTitle:@"副指标" forState:UIControlStateNormal];
    [button2 addTarget:self
                action:@selector(minorPlotChangeIndexButtonClicked:)
      forControlEvents:UIControlEventTouchUpInside];
    self.chartView.minorPlotLeftButtons = @[button2];
    
    
    
    
}

- (void)minorPlotChangeIndexButtonClicked:(UIButton *)button {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"选副指标" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
    [self.chartView.minorPlots enumerateObjectsUsingBlock:^(MPlot *plot, NSUInteger idx, BOOL * _Nonnull stop) {
        [actionSheet addButtonWithTitle:plot.title];
    }];
    [actionSheet showInView:self.view];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    self.chartView.minorPlotIndex = buttonIndex - 1;
    MPlot *plot = self.chartView.minorPlots[buttonIndex - 1];
    UIButton *but = self.chartView.minorPlotLeftButtons[0];
    [but setTitle:plot.title forState:UIControlStateNormal];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.seg.frame = CGRectMake(5, 5, CGRectGetWidth(self.view.frame) - 10, 30);

    self.chartView.frame = CGRectMake(5, CGRectGetMaxY(self.seg.frame) + 5, CGRectGetWidth(self.view.frame) - 10, MIN(300, CGRectGetHeight(self.view.frame) - CGRectGetMaxY(self.seg.frame) - 5));
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.timer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(fetch) userInfo:nil repeats:YES];
    [self.timer fire];
    [self fetch];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.timer invalidate];
}

#pragma mark - private
- (void)fetch {
    [self.chartView reloadData];
}

#pragma mark - event
- (void)segChanged:(UISegmentedControl *)seg {
    if (seg.selectedSegmentIndex == 0) {
        ((MTrendChartPlot *)self.chartView.majorPlots.firstObject).type = MTrendChartTypeOneDay;
        ((MTrendChartTheme *)self.chartView.theme).type = MTrendChartTypeOneDay;
    } else {
        ((MTrendChartPlot *)self.chartView.majorPlots.firstObject).type = MTrendChartTypeFiveDays;
        ((MTrendChartTheme *)self.chartView.theme).type = MTrendChartTypeFiveDays;
    }
    [self.chartView reloadData];
}

- (void)startEnquiry:(NSNotification *)notification {
    MOHLCItem *item = notification.object;
    NSString *string = [NSString stringWithFormat:@"%@:%@:%@:%@:%@",
                        item.closePrice,
                        item.averagePrice,
                        item.amount,
                        item.tradeVolume?:@"-",
                        item.datetime];
    self.navigationItem.title = string;
}

- (void)endEnquiry:(NSNotification *)notification {
    self.navigationItem.title = nil;
}

@end

#endif
